package com.news.servlet;

import com.news.model.News;
import com.news.service.NewsService;
import com.news.service.impl.NewsServiceImpl;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/search")
public class SearchServlet extends HttpServlet {
    private NewsService newsService = new NewsServiceImpl();
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            request.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;charset=UTF-8");
            
            String keyword = request.getParameter("keyword");
            if (keyword != null && !keyword.trim().isEmpty()) {
                List<News> searchResults = newsService.searchNews(keyword);
                request.setAttribute("keyword", keyword);
                request.setAttribute("searchResults", searchResults);
                request.setAttribute("resultCount", searchResults != null ? searchResults.size() : 0);
            }
            
            request.getRequestDispatcher("search.jsp").forward(request, response);
        } catch (Exception e) {
            request.setAttribute("message", "搜索出错：" + e.getMessage());
            request.getRequestDispatcher("search.jsp").forward(request, response);
        }
    }
} 